package cn.zmit.kuxi.application;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;

import android.app.Application;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Environment;
import cn.jpush.android.api.JPushInterface;
import cn.zmit.kuxi.contants.Constants;
import cn.zmit.kuxi.image.ImageLoaderConfig;
import cn.zmit.kuxi.request.RequestManager;
import cn.zmit.kuxi.service.JPushService;

import com.lidroid.xutils.util.LogUtils;

/**
 * 全局Application类
 * 
 * @author lena update from 2015-5-21
 * 
 */

public class BaseApplication extends Application {

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate() {
		super.onCreate();
//		//jpush
//		Intent intent = new Intent(this,JPushService.class);
//		startService(intent);
		
		// 捕获Crash异常并处理
		// AppExceptionHandler mAppExceptionHandler = new
		// AppExceptionHandler(this);
		// Thread.setDefaultUncaughtExceptionHandler(mAppExceptionHandler);

		// 全局日志控制
		LogUtils.customTagPrefix = "system.out"; // 设置前缀
		LogUtils.allowI = true; // 是否允许打印
		// 初始化Universal Image Loader
		ImageLoaderConfig.initImageLoader(this, Constants.BASE_IMAGE_CACHE); // 初始化ImageLoadderConfig类
		// 初始化网络请求，启动队列
		RequestManager.getInstance().initRequest();

		// 监听异常
		Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
	}

	private class MyUncaughtExceptionHandler implements
			UncaughtExceptionHandler {

		@Override
		public void uncaughtException(Thread thread, Throwable ex) {
			// System.out.println("异常捕获...");

			// 打印日志到sd卡
			File file = new File(Environment.getExternalStorageDirectory(),
					"crash.log");

			try {
				PrintWriter err = new PrintWriter(file);
				ex.printStackTrace(err);
				err.flush();
				err.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

		}
	}

}
